package com.qdsgjsfk.vision.ui;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.qdsgjsfk.vision.R;
import com.qdsgjsfk.vision.base.BaseApplication;
import com.qdsgjsfk.vision.databinding.ActivityFaceDetectorBinding;
import com.rest.business.RestProxy;
import com.rest.response.BaseJsonResponse;
import com.rest.response.FaceResponse;
import com.rest.response.QualifiedResponse;

import java.io.File;
import java.util.List;

import io.fotoapparat.Fotoapparat;
import io.fotoapparat.FotoapparatSwitcher;
import io.fotoapparat.facedetector.Rectangle;
import io.fotoapparat.facedetector.processor.FaceDetectorProcessor;
import io.fotoapparat.parameter.LensPosition;
import io.fotoapparat.photo.BitmapPhoto;
import io.fotoapparat.result.PendingResult;
import io.fotoapparat.result.PhotoResult;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.LogUtil;

import com.qdsgjsfk.vision.base.BaseAppCompatActivity;
import com.qdsgjsfk.vision.util.BitmapUtil;
import com.qdsgjsfk.vision.util.NetUtil;

import static io.fotoapparat.log.Loggers.fileLogger;
import static io.fotoapparat.log.Loggers.logcat;
import static io.fotoapparat.log.Loggers.loggers;
import static io.fotoapparat.parameter.selector.LensPositionSelectors.lensPosition;

/**
 * Created by HP on 2019/11/20.
 */

public class FaceDetectorActivity extends BaseAppCompatActivity {

    private ActivityFaceDetectorBinding binding;
    private FotoapparatSwitcher fotoapparatSwitcher;
    private Fotoapparat frontFotoapparat;
    private Fotoapparat backFotoapparat;
    private String studentId;
    private boolean flag = true;
    private boolean waitFlag = true;
    private int faceType = -1;
    private String taskId;
    private String studentName;
    private long firstTime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        binding = DataBindingUtil.setContentView( this, R.layout.activity_face_detector );
        frontFotoapparat = createFotoapparat( LensPosition.FRONT );
        backFotoapparat = createFotoapparat( LensPosition.BACK );
        fotoapparatSwitcher = FotoapparatSwitcher.withDefault( backFotoapparat );
        studentId = getIntent().getStringExtra( "studentId" );
        faceType = getIntent().getIntExtra( "faceType", -1 );
        taskId = getIntent().getStringExtra( "taskId" );
        studentName = getIntent().getStringExtra( "studentName" );
        binding.setStudentName( studentName );
        binding.setHandlers( new EventHandlers() );
        fotoapparatSwitcher.start();
        binding.switchCamera.setOnClickListener( v -> switchCamera() );
    }

    private void switchCamera() {
        if (fotoapparatSwitcher.getCurrentFotoapparat() == frontFotoapparat) {
            fotoapparatSwitcher.switchTo( backFotoapparat );
        } else {
            fotoapparatSwitcher.switchTo( frontFotoapparat );
        }
    }

    private Fotoapparat createFotoapparat(LensPosition position) {
        return Fotoapparat
                .with( this )
                .into( binding.cameraView )
                .lensPosition( lensPosition( position ) )
                .frameProcessor(
                        FaceDetectorProcessor.with( this )
                                .listener( faces -> {
                                    Log.d( "&&&", "Detected faces: " + faces.size() );
                                    long secondTime = System.currentTimeMillis();
                                    if (secondTime - firstTime > 2000 && waitFlag) {
                                        firstTime = secondTime;
                                        System.out.println( secondTime - firstTime );
                                    } else {
                                        waitFlag = false;
                                        if (fotoapparatSwitcher.getCurrentFotoapparat() == backFotoapparat) {
                                            if (faces.size() == 2 && flag) {
                                                PhotoResult result = backFotoapparat.takePicture();
                                                flag = false;
                                                result.toBitmap().whenDone( bitmapPhoto -> {

                                                    Bitmap newBp = BitmapUtil.rotateBitmap( bitmapPhoto.bitmap, 90f );
                                                    if (faceType == 0) {
                                                        updateFace( studentId, BitmapUtil.saveBitmapFile( newBp, studentId + ".jpg" ) );
                                                    } else if (faceType == 1) {
                                                        detectFace( taskId, BitmapUtil.saveBitmapFile( newBp, "temp.jpg" ) );
                                                    } else if (faceType == 2) {
                                                        resetFace( studentId, BitmapUtil.saveBitmapFile( newBp, studentId + ".jpg" ) );
                                                    }
                                                } );
                                            }
                                        }
                                        if (fotoapparatSwitcher.getCurrentFotoapparat() == frontFotoapparat) {
                                            if (faces.size() == 2 && flag) {
                                                PhotoResult result = frontFotoapparat.takePicture();
                                                flag = false;
                                                result.toBitmap().whenDone( bitmapPhoto -> {
                                                    Bitmap newBp = BitmapUtil.rotateBitmap( bitmapPhoto.bitmap, -90f );
                                                    if (faceType == 0) {
                                                        updateFace( studentId, BitmapUtil.saveBitmapFile( newBp, studentId + ".jpg" ) );
                                                    } else if (faceType == 1) {
                                                        detectFace( taskId, BitmapUtil.saveBitmapFile( newBp, "temp.jpg" ) );
                                                    } else if (faceType == 2) {
                                                        resetFace( studentId, BitmapUtil.saveBitmapFile( newBp, studentId + ".jpg" ) );
                                                    }
                                                } );
                                            }
                                        }
                                        binding.rectanglesView.setRectangles( faces );
                                    }
                                } )
                                .build()
                )
                .logger( loggers(
                        logcat(),
                        fileLogger( this )
                ) )
                .build();
    }


    private void updateFace(String studentId, File file) {
        RestProxy.getInstance().updateFace( studentId, file, new Observer<FaceResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
                flag = false;
                Toast.makeText( FaceDetectorActivity.this, "正在上传", Toast.LENGTH_SHORT ).show();
            }

            @Override
            public void onNext(FaceResponse faceResponse) {
                finish();
                Toast.makeText( FaceDetectorActivity.this, "操作成功", Toast.LENGTH_SHORT ).show();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                NetUtil.onError( e, FaceDetectorActivity.this );
                flag = true;
            }

            @Override
            public void onComplete() {

            }
        } );
    }


    private void resetFace(String studentId, File file) {
        RestProxy.getInstance().resetFace( studentId, file, new Observer<FaceResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
                flag = false;
                Toast.makeText( FaceDetectorActivity.this, "正在上传", Toast.LENGTH_SHORT ).show();
            }

            @Override
            public void onNext(FaceResponse faceResponse) {
                finish();
                Toast.makeText( FaceDetectorActivity.this, "操作成功", Toast.LENGTH_SHORT ).show();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                NetUtil.onError( e, FaceDetectorActivity.this );
                flag = true;
            }

            @Override
            public void onComplete() {

            }
        } );
    }

    private void detectFace(String taskId, File file) {

        RestProxy.getInstance().detectFace( taskId, file, new Observer<FaceResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
                flag = false;
                Toast.makeText( FaceDetectorActivity.this, "正在上传", Toast.LENGTH_SHORT ).show();
            }

            @Override
            public void onNext(FaceResponse faceResponse) {
                Toast.makeText( FaceDetectorActivity.this, "操作成功", Toast.LENGTH_SHORT ).show();
                //人脸返回之后，请求接口。看看是否有其他项
                Intent intMain;
                LogUtil.e( "配置其他项" + BaseApplication.isShowOther );
                if (BaseApplication.isShowAxis || BaseApplication.isShowOther) {
                    intMain = new Intent( getApplicationContext(), StudentDetailOtherActivity.class );
                } else {
                    intMain = new Intent( getApplicationContext(), StudentDetailActivity.class );
                }
                Bundle bd = new Bundle();
                bd.putString( "studentId", faceResponse.data.studentId );
                bd.putString( "taskId", taskId );
                intMain.putExtras( bd );
                startActivity( intMain );
                finish();

            }

            @Override
            public void onError(Throwable e) {
                NetUtil.onError( e, FaceDetectorActivity.this );
                finish();
                e.printStackTrace();
//                flag = true;
            }

            @Override
            public void onComplete() {

            }
        } );
    }

    @Override
    protected void onDestroy() {
        fotoapparatSwitcher.stop();
        super.onDestroy();

    }
}
